package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户的地理位置
     *
     * @param userId
     * @param x       经度
     * @param y       纬度
     * @param addrStr
     */
    @Override
    public void save(Long userId, Double x, Double y, String addrStr) {
        //1. 构建条件判断是否存在
        Query query = new Query(Criteria.where("userId").is(userId));
        // 坐标点
        GeoJsonPoint point = new GeoJsonPoint(x,y);
        long timeMillis = System.currentTimeMillis();
        if (mongoTemplate.exists(query, UserLocation.class)) {
            //2. 存在则更新
            Update update = new Update();
            update.set("address", addrStr);
            update.set("location", point);
            update.set("updated", timeMillis);

            mongoTemplate.updateFirst(query, update, UserLocation.class);
        }else {
            //3. 不存在则添加
            UserLocation userLocation = new UserLocation();
            userLocation.setLocation(point);
            userLocation.setCreated(timeMillis);
            userLocation.setUserId(userId);
            userLocation.setAddress(addrStr);
            userLocation.setUpdated(timeMillis);
            mongoTemplate.insert(userLocation);
        }
    }

    /**
     * 搜附近
     *
     * @param userId
     * @param distance 单位米
     * @return 查询到的用户id
     */
    @Override
    public List<Long> searchNearBy(Long userId, Long distance) {
        List<Long> list = new ArrayList<>();
        //1. 查询用户的坐标, 作为圆心
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        // 刚注册不到5分钟。
        if(null == userLocation){
            return list;
        }
        //2. 构建半径, 单位是km, 距离要换算
        Distance radius = new Distance(distance/1000, Metrics.KILOMETERS);
        //3. 创建圆
        Circle circle = new Circle(userLocation.getLocation(), radius);
        //4. 构建查询条件, 以圆为条件，location为条件
        Query locationQuery = new Query(Criteria.where("location").withinSphere(circle)
                //同时要排除登录者
                .and("userId").ne(userId));
        //5. 查询结果
        List<UserLocation> locationList = mongoTemplate.find(locationQuery, UserLocation.class);
        if(CollectionUtil.isNotEmpty(locationList)){
            list = locationList.stream().map(UserLocation::getUserId).collect(Collectors.toList());
        }
        return list;
    }
}
